package com.developer.loginsample.activity;

import com.developer.loginsample.R;
import com.developer.loginsample.util.Util;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

	private EditText txtUsername;
	private EditText txtPassword;
	private Button btnLogin;
	private TextView lblSignup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_login);
		initializeComponents();
		registerListeners();
	}

	private void initializeComponents() {
		txtUsername = (EditText) findViewById(R.id.txt_login_username);
		txtPassword = (EditText) findViewById(R.id.txt_login_password);
		btnLogin = (Button) findViewById(R.id.btn_login);
		lblSignup = (TextView) findViewById(R.id.lbl_signup);
	}

	private void registerListeners() {
		btnLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setProgressBarIndeterminateVisibility(true);
				String username = txtUsername.getText().toString();
				String password = txtPassword.getText().toString();
				if (username.isEmpty() || password.isEmpty()) {
					Util.showAlertDialog(LoginActivity.this, "Username or Password cannot be empty.");
					setProgressBarIndeterminateVisibility(false);
				} else {
					ParseUser.logInInBackground(username, password, new LogInCallback() {
						@Override
						public void done(ParseUser user, ParseException exception) {
							setProgressBarIndeterminateVisibility(false);
							if (exception == null) {
								Util.redirectActivity(LoginActivity.this, MainActivity.class);
							} else {
								Util.showAlertDialog(LoginActivity.this, exception.getMessage());
							}
						}
					});
				}
			}
		});
		lblSignup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
				startActivity(intent);
			}
		});
	}
}
